#-*- coding: utf-8 -*-
from odoo import models, fields, api
from odoo.exceptions import Warning
from odoo.tools.translate import _
import odoo.addons.decimal_precision as dp
from datetime import datetime

# class TransientImportBom(models.TransientModel):
class TransientImportBom(models.Model):
    _name = 'import.bom.transient'
    _rec_name = ''
    _description = 'import bom'

    bom_line_ids = fields.One2many('import.bom.line.transient', 'mrp_bom_id', u'明细', copy=True)
    bom_id = fields.Many2one('mrp.bom',u'清单bom')
    code = fields.Char(u'编码')
    name = fields.Char(u'名称')
    type = fields.Selection([('normal', 'Normal'), ('phantom', 'Set')], u'BoM类型')

    # product_id =  fields.Many2one('product.product', 'Product Variant')

    product_qty = fields.Float(u'数量', required=True,default=1, digits_compute=dp.get_precision('Product Unit of Measure'))
    # product_uom  = fields.Many2one('product.uom', 'Product Unit of Measure', required=True, help="Unit of Measure (Unit of Measure) is the unit of measurement for the inventory control")

    # computed_uom  = fields.Many2one('product.uom', u'导入单位',compute ='_compute_uom')
    computed_product_id = fields.Many2one('product.product', u'导入产品')

    note = fields.Char(u'导入说明')


    error_message = fields.Char(u'验证详情')
    can_import = fields.Boolean(u'验证结果')
    is_existed = fields.Boolean(u'已存在')

    def prepare_import(self):
        if self.can_import:
            return {'product_id': self.computed_product_id.id,
                    'user_id':self._uid,
                    'product_qty': self.product_qty,
                    'product_uom' : self.computed_product_id.uom_id.id,
                    # 'name': u"【"+self.computed_product_id.default_code+u"】"+self.computed_product_id.product_tmpl_id.name,
                    # 'name': self.name,
                    # 'type': self.type,
                    # 'bom_line_ids': [(0,0,{'product_id': line.computed_product_id.id, 'product_qty': line.product_qty, 'product_uom': line.computed_product_id.uom_id.id,'product_tmpl_id':line.computed_product_id.product_tmpl_id.id, 'type': line.type}) for line in self.bom_line_ids]
                    'mrp_bom_lines': [(0,0,{'name':line.computed_product_id.display_name,
                                            'product_id': line.computed_product_id.id,
                                            'product_qty': line.product_qty,
                                            'product_uom': line.computed_product_id.uom_id.id,
                                            'attrition_rate': line.attrition_rate,
                                            'attrition_fixed': line.attrition_fixed,
                                            'part_number': line.part_number,
                                            }) for line in self.bom_line_ids]
            }
        else:
            return None
    @api.one
    def verify(self):
        self.error_message = u''

        products = None
        if self.code:
            products = self.env['product.product'].search([('default_code','=',self.code)])
        if not products and self.name:
            products = self.env['product.product'].search([('name','=',self.name)])

        if products:
            self.computed_product_id = products[0]
            if self.env['mrp.bom'].mrp_bom_find(product = self.computed_product_id):
                self.is_existed = True
                self.can_import = False
                self.error_message += u'BoM已存在'
            else:
                self.is_existed = False
            i = 0
            for line in self.bom_line_ids:
                line.error_message = u''
                line_products = None
                line_products_code = None
                line.computed_product_id = None
                i+=1
                if line.code:
                    line_products_code = self.env['product.product'].search([('default_code','=',line.code)])
                else:
                    self.can_import = False
                    line_products_name = self.env['product.product'].search([('name','=',line.name)])
                    if line_products_name and len(line_products_code._ids)==1:
                        line_products = line_products_code.product_variant_ids
                        line.computed_product_id = line_products[0]
                    # elif line_products_name and len(line_products_code._ids)>1:
                    #     line.error_message += u'警告：【第'+str(i)+u'行，'+u'一个规格对应多个产品!】'
                    line.error_message += u'【第'+str(i)+u'行，'+u'没有编码!】'
                if not line.product_qty:
                    line.error_message += u'【第'+str(i)+u'行，'+u'数量不对!】'
                if line_products_code and len(line_products_code._ids)==1:
                    line_products = line_products_code.product_variant_ids
                elif line_products_code and len(line_products_code._ids)>1:
                    self.can_import = False
                    line.error_message += u'警告：【第'+str(i)+u'行，'+u'一个编码对应多个产品!】'
                else:
                    self.can_import = False
                    line.error_message += u'【第'+str(i)+u'行，'+u'没找到编码对应的产品!】'
                if line_products_code and len(line_products_code._ids)==1 and line_products_code.name <> line.name:
                    self.can_import = False
                    line.error_message += u'【第'+str(i)+u'行，'+u'明细产品编码和名称不匹配!】'
                # if line_products_code and len(line_products_code._ids)==1 and line_products_code.name_second <> line.name_second:
                #     self.can_import = False
                #     line.error_message += u'【第'+str(i)+u'行，'+u'明细产品编码和规格不匹配!】'
                if line_products:
                    line.computed_product_id = line_products[0]
            if all([l.computed_product_id and not l.error_message for l in self.bom_line_ids]):
                self.can_import = True
            else:
                self.can_import = False
                self.error_message += u'明细有问题,请检查'
        else:
            self.error_message += u'产品不存在'
            self.can_import = False

    @api.multi
    def start_import(self):
        for i in self:
            if i.can_import and not i.is_existed:
                bom_id = self.env['mrp.bom'].create(i.prepare_import())
                i.is_existed = True
                i.bom_id = bom_id

    @api.one 
    @api.depends('name','code')
    def _compute_product(self):
        products = self.env['product.product'].search(['|',('name','=',self.name),('default_code','=',self.code)])
        if products:
            self.computed_product_id = products[0]

    # @api.one 
    # @api.depends('category')
    # def _compute_category(self):
    #     categories = self.env['product.category'].search([('name','=',self.category)])
    #     if categories:
    #         self.computed_category_id = categories[0]
    
    def import_data_transformer(self, row):
        return row

    def import_data_filter(self, row):
        # if u'父零件' in row:
        #     self.env.context['curreent_parent_bom_row'] = row
        #     return False
        return True


# class TransientImportBomLine(models.TransientModel):
class TransientImportBomLine(models.Model):
    _name = 'import.bom.line.transient'
    _description = 'import bom line'

    code = fields.Char(u'编码')
    name = fields.Char(u'名称')
    notes = fields.Char(u'备注')
    # name_second = fields.Char(u'规格')

    # uom = fields.Char(u'单位')
    error_message = fields.Char(u'验证详情')
    product_qty = fields.Float(u'数量', required=True, digits_compute=dp.get_precision('Product Unit of Measure'))
    attrition_rate = fields.Float(u'耗损率', digits=(16, 3), default=0.0)
    attrition_fixed = fields.Float(u'固定耗损', default=0.0)
    part_number = fields.Float(u'粒数', default=0.0)
    mrp_bom_id = fields.Many2one('import.bom.transient', u'上级Bom')

    # computed_uom  = fields.Many2one('product.uom', u'导入单位',compute ='_compute_uom')
    computed_product_id = fields.Many2one('product.product', u'导入产品')

    # type = fields.Selection([('normal', 'Normal'), ('phantom', 'Phantom')], u'类型', required=True)

    note = fields.Char(u'导入说明')

    # @api.one 
    # @api.depends('uom')
    # def _compute_uom(self):
    #     uoms = self.env['product.uom'].search([('name','=',self.name)])
    #     if uoms:
    #         self.computed_uom = uoms[0]
    @api.one 
    @api.depends('name')
    def _compute_product(self):
        products = self.env['product.product'].search([('name','=',self.name)])
        if products:
            self.computed_product_id = products[0]

    # @api.one 
    # @api.depends('category')
    # def _compute_category(self):
    #     categories = self.env['product.category'].search([('name','=',self.category)])
    #     if categories:
    #         self.computed_category_id = categories[0]
    
    def import_data_transformer(self, row):
        return row

    def import_data_filter(self, row):
        # if u'父零件' in row:
        #     self.env.context['curreent_parent_bom_row'] = row
        #     return False
        return True

